package com.seasun.xg.claw;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class StaticConfigurationLoader {

	private static final Logger logger = LoggerFactory.getLogger(StaticConfigurationLoader.class);
	private static StaticConfigurationProperties conf = new StaticConfigurationProperties();

	public static void init() {
		loadProperties();

		if (conf.isEnable()) {
			List<String> hosts = conf.getConfHostsList();

			for (String host : hosts) {
				if (loadRemoteConfigurations(host)) {
					break;
				}
			}
		}
	}

	private static boolean loadRemoteConfigurations(String host) {
		try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
			HttpGet httpget = new HttpGet(String.format("%s/list/%s/%s/%s/%s/", host, conf.appGroup, conf.appName,
					conf.appVersion, conf.appProfile));

			logger.debug("RequestLine: {}", httpget.getRequestLine());

			// Create a custom response handler
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

				@Override
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity) : null;
					}

					throw new ClientProtocolException("Unexpected response status: " + status);
				}

			};
			String responseBody = httpclient.execute(httpget, responseHandler);

			httpclient.execute(httpget, response -> {
				return "";
			} );

			System.out.println("----------------------------------------");
			System.out.println(responseBody);
		} catch (IOException e) {
			logger.error("", e);
		}

		return true;
	}

	private static void loadProperties() {
		try (InputStream in = StaticConfigurationLoader.class.getResourceAsStream("/claw-conf-server.properties")) {
			Properties prop = new Properties();

			prop.load(in);

			conf.confEnable = Optional.ofNullable(prop.getProperty("conf.enable")).orElse("true");
			conf.confHosts = Optional.ofNullable(prop.getProperty("conf.hosts")).orElse("127.0.0.1:7731");
			conf.confIgnores = Optional.ofNullable(prop.getProperty("conf.ignores")).orElse("");
			conf.appGroup = Optional.ofNullable(prop.getProperty("app.group")).orElse("");
			conf.appName = Optional.ofNullable(prop.getProperty("app.name")).orElse("");
			conf.appVersion = Optional.ofNullable(prop.getProperty("app.version")).orElse("1.0.0.0");
			conf.appProfile = Optional.ofNullable(prop.getProperty("app.profile")).orElse("default");
		} catch (IOException e) {
			logger.error("", e);
		}
	}

}
